<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer
    v-bind="$attrs"
    :showFooter="true"
    :okAuth="'rd:pack:rdPack:edit'"
    @register="registerDrawer"
    @ok="handleSubmit"
    width="80%"
  >
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>
    </template>
    <BasicForm @register="registerForm">
      <template #rdPackCList>
        <BasicTable @register="registerRdPackCTable" @row-click="handleRdPackCRowClick" />
        <a-button class="mt-2" @click="handleRdPackCAdd" v-auth="'rd:pack:rdPack:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsRdPackRdPackForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { RdPack, rdPackSave, rdPackForm } from '/@/api/wms/rd/pack/rdPack';
  import { max } from 'lodash-es';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('rd.pack.rdPack');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref<RdPack>({} as RdPack);

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增拣货任务') : t('编辑拣货任务'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('拣货单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: -1,
      },
      dynamicDisabled: true,
    },
    {
      label: t('单据日期'),
      field: 'ddate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        showTime: false,
        valueFormat: 'YYYY-MM-DD',
      },
      required: true,
    },
    {
      label: t('拣货方式'),
      field: 'packType',
      component: 'Select',
      componentProps: {
        dictType: 'wms_pick_type',
        allowClear: true,
      },
      required: true,
    },
    {
      label: t('制单人名称'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('修改人名称'),
      field: 'updateByName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
      },
      dynamicDisabled: true,
    },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('拣货明细'),
      field: 'rdPackCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'rdPackCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerRdPackCTable, rdPackCTable] = useTable({
    actionColumn: {
      width: 60,
      actions: (record: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleRdPackCDelete.bind(this, record),
          },
          auth: 'rd:pack:rdPack:edit',
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setRdPackCTableData(_res: Recordable) {
    rdPackCTable.setColumns([
      {
        title: t('子表ID'),
        dataIndex: 'cid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: true,
        ifShow: false,
      },
      {
        title: t('发货单行号'),
        dataIndex: 'fentryid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('订单号'),
        dataIndex: 'forderno',
        width: 120,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('订单行号'),
        dataIndex: 'forderentryid',
        width: 80,
        align: 'center',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('订单主表ID'),
        dataIndex: 'forderid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('收货地址'),
        dataIndex: 'faddress',
        width: 230,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('打包单位'),
        dataIndex: 'fcustomerdb',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('收货单位'),
        dataIndex: 'fcustomersh',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('收货联系人'),
        dataIndex: 'fperson',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('电话'),
        dataIndex: 'fphone',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 20,
        },
        editRule: false,
      },
      {
        title: t('手机'),
        dataIndex: 'fmobilephone',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 20,
        },
        editRule: false,
      },
      {
        title: t('物料内码'),
        dataIndex: 'fitemid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('物料代码'),
        dataIndex: 'fitemno',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('物料名称'),
        dataIndex: 'fitemname',
        width: 230,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('数量'),
        dataIndex: 'fqty',
        width: 80,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 26,
        },
        editRule: false,
      },
      {
        title: t('重量'),
        dataIndex: 'fweight',
        width: 80,
        align: 'right',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 26,
        },
        editRule: false,
      },
      {
        title: t('辅助属性类别'),
        dataIndex: 'f109',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('仓库ID'),
        dataIndex: 'fstockid',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
        ifShow: false,
      },
      {
        title: t('仓库编码'),
        dataIndex: 'fstockno',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 64,
        },
        editRule: false,
      },
      {
        title: t('仓库名称'),
        dataIndex: 'fstockname',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('品质'),
        dataIndex: 'fpz',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
      {
        title: t('要求到货日期'),
        dataIndex: 'freturndate',
        width: 215,
        align: 'center',
        editRow: true,
        editComponent: 'DatePicker',
        editComponentProps: {
          format: 'YYYY-MM-DD HH:mm',
          showTime: { format: 'HH:mm' },
        },
        editRule: false,
      },
      {
        title: t('形象刊'),
        dataIndex: 'cfree1',
        width: 130,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
        editRule: false,
      },
      {
        title: t('行备注'),
        dataIndex: 'fremarks',
        width: 230,
        align: 'left',
        editRow: true,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 255,
        },
        editRule: false,
      },
    ]);
    rdPackCTable.setTableData(record.value.rdPackCList || []);
  }

  function handleRdPackCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleRdPackCAdd() {
    rdPackCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleRdPackCDelete(record: Recordable) {
    rdPackCTable.deleteTableDataRecord(record);
  }

  async function getRdPackCList() {
    let rdPackCListValid = true;
    let rdPackCList: Recordable[] = [];
    for (const record of rdPackCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        rdPackCListValid = false;
      }
      rdPackCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of rdPackCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      rdPackCList.push({
        ...record,
        status: '1',
      });
    }
    if (!rdPackCListValid) {
      throw { errorFields: [{ name: ['rdPackCList'] }] };
    }
    return rdPackCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    const res = await rdPackForm(data);
    record.value = (res.rdPack || {}) as RdPack;
    record.value.__t = new Date().getTime();
    setFieldsValue(record.value);
    setRdPackCTableData(res);
    setDrawerProps({ loading: false });
  });

  async function handleSubmit() {
    try {
      const data = await validate();
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      data.rdPackCList = await getRdPackCList();
      // console.log('submit', params, data, record);
      const res = await rdPackSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      setDrawerProps({ confirmLoading: false });
    }
  }
</script>
